import 'dart:async';
import 'dart:convert';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/login_textfield.dart';
import 'package:find_friend/root/root_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:page_transition/page_transition.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';


class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {

  bool isshowclear = false;
  bool havepwd = false;
  String code = "";
  String rightCode = "";
  int resentCode = 59;
  String resetString = "";
  String label_login = "登陆/注册";
  bool _iscan_login = false;
  bool _isverify_code = true;
  Timer _timer;
  final _phoneFoucs = FocusNode();
  final _pwdFoucs = FocusNode();
  final _codeFoucs = FocusNode();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _pwdController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _pwdController.dispose();
    _codeController.dispose();
    _stopTimer();
    super.dispose();
  }

  void _loginAction() {

    if(_phoneController.text == "") {
      AlertTool.showToast("请输入手机号码");
      return;
    }
    // 1: 密码登陆，2:验证码登陆
    String code = havepwd ? _pwdController.text : _codeController.text;
    Map<String, dynamic> params;
    if(havepwd){
      params = {"account":_phoneController.text, "password":code};
    } else {
      params = {"mobile": _phoneController.text, "code":code};
    }

    AlertTool.showLoadingDialog(context);
    String url = havepwd ? API.pwd_login : API.login;
    Networktool.request(url, params: params, success: (data) async {
      if(data["data"] != null) {
        SharedPreferences share = await SharedPreferences.getInstance();
        String tempJS = json.encode(data["data"]);
        share.setString(KEY_userjosn_info, tempJS);
        share.setString(KEY_user_token, data["data"]["token"].toString());
        _jumpToRoot(data);
      }
    },
    fail: (data) async { 
      if(data.contains("Password")) {
        bool isok = await AlertTool.showConfirmDialog(context,
          title: "账号或登陆密码错误\n请重新输入",
          cancel: "忘记密码？",
          sure: "重新输入"
        );
        if(isok) {
          _pwdFoucs.requestFocus();
        } else {
          if(_phoneController.text.length == 11) {
                Navigator.of(context).pushNamed("/forget",arguments: _phoneController.text);
          } else {
            AlertTool.showToast("请输入手机号码");
          }
        }
      } else {
        AlertTool.showToast(data);
      }
    }, finaly: (){
      Navigator.of(context).pop();
    });
  }

  _clear() {
    _codeController.clear();
    _pwdController.clear();
    setState(() {
      code = "";
    });
  }

  _requestIsregist() {
    String phone = _phoneController.text;
    _clear();
    if(phone.length != 11){
      AlertTool.showToast("请输入11位手机号码");
      return;
    } 
    if(resentCode != 59) {
      AlertTool.showToast("您的操作太快了，休息一下吧！");
      return;
    }
    AlertTool.showLoadingDialog(context);
    Networktool.request(API.checkreg, params: {"mobile": phone}, success: (data){
      if(data["data"] != null){
        setState(() {
          havepwd = data["data"]["password"] == true; // isregist 用于判断UI。 
          label_login = "登陆";     // 判断登陆逻辑
        });
        if(data["data"]["password"] == null) {
          _sendSMS();
        } else {
          _pwdFoucs.requestFocus();
        }
      }
    },fail: (data){
        setState(() {
          label_login = "注册";
        });
        _sendSMS();
    },finaly: () => Navigator.of(context).pop());
  }

  _jumpToRoot(data) {

    bool canpop = Navigator.of(context).canPop();
    final wid = PageTransition(
                  child: RootPage(),
                  type: PageTransitionType.fade,
                );
    if(canpop == false){
      Navigator.of(context).pushReplacement(wid);
    } else {
      Navigator.of(context).pushAndRemoveUntil(wid,(Route<dynamic> route) => false);
    }
    
  }

  _stopTimer() {
    if(_timer == null) return;
    _timer.cancel();
    _timer = null;
  }

  _beginTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(resentCode == 1) {
        _stopTimer();
        resentCode = 59;
        setState(() {
          resetString = "";
        });
      } else {
        resentCode -= 1;
        setState(() {
          resetString = "($resentCode)";
        });
      }
    });
  }

  void _sendSMS() {
    if(_phoneController.text.length != 11) {
      AlertTool.showToast("请输入11位手机号码");
      return;
    }
    if(resentCode == 59) {
      _clear();
      _codeFoucs.requestFocus();
      Networktool.request(API.code, params: {"mobile":_phoneController.text},success:(data){
        print(data);
        if(data["data"] != null) {
          rightCode = data["data"]["code"].toString();
          AlertTool.showToast(rightCode);
          _beginTimer();
        }
      },);
    } else {
      AlertTool.showToast("您的操作太快了，休息一下吧！");
    }
  }

  // 进入主页
  _enterHome() {
    _loginAction();
  }

  _initPwd() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        SizedBox(height: 30,),
        Container(
          alignment: Alignment.centerLeft,
          child: Text("输入密码后点击开始进入找他社区交友吧～", style: instanceTextStyle(11, APP_font_grey),)
        ),
        LoginTextField(
            controller: _pwdController,
            obscureText: true,
            marginTop: 30,
            placeholder: "请输入密码",
            maxlength: -1,
            focusNode: _pwdFoucs,
            callback: (str){
              setState(() {
                _iscan_login = str.length >= 6;
              });
            },
          ),
          GestureDetector(
            child: Container(
              padding: const EdgeInsets.only(right: 5, top: 10),
              child: Text("忘记密码?", 
              style: instanceTextStyle(
                11,
                APP_main_color,
                decoration: TextDecoration.underline
              )),
            ),
            onTap: (){
              if(_phoneController.text.length == 11) {
                Navigator.of(context).pushNamed("/forget",arguments: _phoneController.text);
              } else {
                AlertTool.showToast("请输入手机号码");
              }
            },
          )
      ],
    );
  }

  String _getCodeString(int index) {
    if(index < code.length) {
      return code[index];
    } else {
      return "";
    }
  }

  // 创建验证码输入框
  _initVerifyCode() {
    TextStyle style = instanceTextStyle(15, Colors.black, fontWeight: FontWeight.bold);
    return Stack(
      children: [
        Container(
          padding: const EdgeInsets.only(top: 30),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("输入您的验证码叭～", style: instanceTextStyle(11, APP_font_grey),),
              SizedBox(height: 40,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(4, (index) => 
                Container(
                    width: 50,
                    height: 40,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(
                        color: _getCodeString(index) == "" ? Colors.black : (_isverify_code ? APP_main_color : APP_verify_error_color), width: 1.5)
                    ),
                    child: Text(_getCodeString(index), style: style),
                  )),
              ),
              Container(
                padding: const EdgeInsets.only(top: 20),
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  child: RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(text: "重新发送验证码",style: instanceTextStyle(11, APP_main_color, fontWeight: FontWeight.bold, decoration: TextDecoration.underline)),
                        TextSpan(text: resetString,style: instanceTextStyle(11, APP_main_color, fontWeight: FontWeight.bold)),
                      ]
                    ),
                  ),
                  onTap: _sendSMS,
                ),
              )
            ],
          ),
        ),
        Container(
          height: 130,
          child: TextField(
            controller: _codeController,
            showCursor: false,
            maxLength: 4,
            focusNode: _codeFoucs,
            style: TextStyle(color: Colors.transparent),
            keyboardType: TextInputType.number,
            inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
            decoration: InputDecoration(
              border: InputBorder.none,
              counterText: "",
            ),
            onChanged: (str){
              setState(() {
                code = str;
                if(str.length == 4) {
                  _isverify_code = str == rightCode;
                  _iscan_login = _isverify_code;
                  if(_iscan_login == true){ // 如果验证码正确关闭键盘
                    _codeFoucs.unfocus();
                  }
                } else {
                  _isverify_code = true;
                }
              });
              if(_isverify_code == false && str.length == 4) {
                AlertTool.showToast("验证码有误");
              }
            },
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomPadding: false,
      body: SafeArea(
        top: false,
              child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            _phoneFoucs.unfocus();
            _pwdFoucs.unfocus();
            _codeFoucs.unfocus();
          },
          child: Container(
              padding: const EdgeInsets.only(left: 40, right: 40),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: EdgeInsets.only(top: size.width * 0.3, bottom: 30),
                    child: Text(label_login, style: instanceTextStyle(
                      22,
                      Colors.black,
                      fontWeight: FontWeight.bold
                    ),),
                  ),
                  Text(
                    "输入您的手机号，未注册手机请注意查看验证码哦～",
                    style: instanceTextStyle(11, APP_font_grey),
                  ),
                  LoginTextField(
                    controller: _phoneController, 
                    placeholder: "请输入手机号登陆或注册", 
                    maxlength: 11,
                    marginTop: size.width * 0.07,
                    keybordType: TextInputType.number,
                    inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                    focusNode: _phoneFoucs,
                    suffixTap: _requestIsregist,
                    suffixIconName: "assets/querensj.png",
                  ),
                  Offstage(
                    offstage: label_login == "登陆/注册", // 还没有查询不显示
                    child: havepwd ? _initPwd():_initVerifyCode(),
                  ),
                  Expanded(child: Container()),
                  Center(
                    child: GestureDetector(
                      excludeFromSemantics: false,
                      onTap: (_iscan_login) ? _enterHome : null,
                      child: Container(
                        height: 40,
                        margin: const EdgeInsets.only(bottom: 30, left: 25, right: 25),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          border: Border.all(color: _iscan_login ? Colors.black : Colors.black45,width: 1.5),
                          borderRadius: BorderRadius.circular(20)
                        ),
                        child: Text("开始找他", style: instanceTextStyle(18, _iscan_login ? Colors.black : Colors.black45,)
                      ),
                      )
                    ),
                  )
                ],
              ),
            ),
        ),
      ),
    );
  }
}